+ function($) {
    "use strict";

    var defaults;

    var format = function(data,showName,codeValue) {
        var result = [];
        for(var i=0;i<data.length;i++) {
            var d = data[i];
            if(/^请选择/.test(d[showName])) continue;
            result.push(d);
        }
        if(result.length) return result;
        return [];
    };

    var sub = function(data,subName,showName,codeValue) {
        if(!data[subName]){
            var aa={},bb=[];
            aa[showName]='';
            aa[codeValue]=data[codeValue];
            bb.push(aa);
            return bb;
        };
        return format(data[subName],showName,codeValue);
    };

    var getTwo = function(d,raw,subName,showName,codeValue) {
        for(var i=0;i< raw.length;i++) {
            if(raw[i][codeValue] === d || raw[i][showName] === d) return sub(raw[i],subName,showName,codeValue);
        }
        return [];
    };

    var getThree = function(p, c,raw,subName,showName,codeValue) {
        for(var i=0;i< raw.length;i++) {
            if(raw[i][codeValue] === p || raw[i][showName] === p) {
                if(raw[i].hasOwnProperty(subName)){
                    for(var j=0;j< raw[i][subName].length;j++) {
                        if(raw[i][subName][j][codeValue] === c || raw[i][subName][j][showName] === c) {
                            return sub(raw[i][subName][j],subName,showName,codeValue);
                        }
                    }
                }else{
                    return [];
                }
            }
        }
    };

    var parseInitValue = function (val,raw,subName,showName,codeValue) {
        var p = raw[0], c = {}, d={};

        var tokens = val.split(' ');
        raw.map(function (t) {
            if (t[showName] === tokens[0]) p = t;
        });
        if(p.hasOwnProperty(subName)){
            p[subName].map(function (t) {
                if (t[showName] === tokens[1]) c = t;
            })
        }
        if (tokens[2]) {
            c[subName].map(function (t) {
                if (t[showName] === tokens[2]) d = t;
            })
        }
        var c_code = c.hasOwnProperty(codeValue)?c[codeValue]:'';
        var d_code = d.hasOwnProperty(codeValue)?d[codeValue]:'';
        if (d) return [p[codeValue], c_code, d_code];
        return [p[codeValue], c_code];
    }

    $.fn.cascadePicker = function(params) {
        params = $.extend({}, defaults, params);
        var raw=params.raw;
        var subName = params.subName;
        var showName = params.showName;
        var codeValue = params.codeValue;
        return this.each(function() {
            var self = this;
            var initOneName = raw.map(function(d) {
                return d[showName];
            });
            var initOneId = raw.map(function(d) {
                return d[codeValue];
            });
            var initTwo= raw[0].length>0?sub(raw[0],subName):[];
            var initTwoName = initTwo.map(function (c) {
                return c[showName];
            });
            var initTwoId = initTwo.map(function (c) {
                return c[codeValue];
            });
            var initThree = raw[0].hasOwnProperty(subName)?sub(raw[0][subName][0],subName):[];

            var initThreeName = initThree.map(function (c) {
                return c[showName];
            });
            var initThreeId = initThree.map(function (c) {
                return c[codeValue];
            });

            var currentOne = initOneName[0];
            var currentTwo = initTwoName[0];
            var currentThree = initThreeName[0];

            var cols = [
                {
                    displayValues: initOneName,
                    values: initOneId,
                    cssClass: "col-one"
                },
                {
                    displayValues: initTwoName,
                    values: initTwoId,
                    cssClass: "col-two"
                }
            ];

            if(params.showThree) cols.push({
                displayValues: initThreeName,
                values: initThreeId,
                cssClass: "col-three"
            });

            var config = {
                cssClass: "cascade-picker",
                rotateEffect: false,  //为了性能
                formatValue: function (p, values, displayValues) {
                    return displayValues.join(' ');
                },
                onChange: function (picker, values, displayValues) {
                    var subName = picker.params.subName;
                    var showName = picker.params.showName;
                    var codeValue = picker.params.codeValue;
                    var newOne = picker.cols[0].displayValue;
                    var newTwo;
                    if(newOne !== currentOne) {
                        var newTwos = getTwo(newOne,raw,subName,showName,codeValue);
                        newTwo = newTwos.length>0?newTwos[0][showName]:'';
                        var newThrees = getThree(newOne, newTwo, raw,subName,showName,codeValue);
                        console.log(newThrees);
                        newThrees = newThrees!=undefined?newThrees:[];
                        picker.cols[1].replaceValues(newTwos.map(function (c) {
                            return c[codeValue];
                        }), newTwos.map(function (c) {
                            return c[showName];
                        }));
                        if(params.showThree) picker.cols[2].replaceValues(newThrees.map(function (d) {
                            return d[codeValue];
                        }), newThrees.map(function (d) {
                            return d[showName];
                        }));
                        currentOne = newOne;
                        currentTwo = newTwo;
                        picker.updateValue();
                        return false; // 因为数据未更新完，所以这里不进行后序的值的处理
                    } else {
                        if(params.showThree) {
                            newTwo = picker.cols[1].displayValue;
                            if(newTwo !== currentTwo) {
                                var threes = getThree(newOne, newTwo, raw,subName,showName,codeValue);
                                picker.cols[2].replaceValues(threes.map(function (d) {
                                    return d[codeValue];
                                }), threes.map(function (d) {
                                    return d[showName];
                                }));
                                currentTwo = newTwo;
                                picker.updateValue();
                                return false; // 因为数据未更新完，所以这里不进行后序的值的处理
                            }
                        }
                    }
                    //如果最后一列是空的，那么取倒数第二列
                    var len = (values[values.length-1] ? values.length - 1 : values.length - 2);
                    len = len==''?values.length - 2:len;
                    $(self).attr('data-code', values[len]);
                    $(self).attr('data-codes', values.join(','));
                    if (params.onChange) {
                        params.onChange.call(self, picker, values, displayValues);
                    }
                },
                cols: cols
            };

            if(!this) return;
            var p = $.extend({}, params, config);
            //计算value
            var val = $(this).val();
            if (!val) val = " ";
            currentOne = val.split(" ")[0];
            currentTwo = val.split(" ")[1];
            currentThree= val.split(" ")[2];
            if(val) {
                p.value = parseInitValue(val,raw,subName,showName,codeValue);
                if(p.value[0]) {
                    var twos = getTwo(p.value[0],raw,subName,showName,codeValue);
                    p.cols[1].values = twos.map(function (c) {
                        return c[codeValue];
                    });
                    p.cols[1].displayValues = twos.map(function (c) {
                        return c[showName];
                    });
                }
                if(p.value[1]) {
                    if (params.showThree) {
                        var three = getThree(p.value[0], p.value[1],raw,subName,showName,codeValue);
                        p.cols[2].values = three.map(function (d) {
                            return d[codeValue];
                        });
                        p.cols[2].displayValues = three.map(function (d) {
                            return d[showName];
                        });
                    }
                } else {
                    if (params.showThree) {
                        var three = getThree(p.value[0], p.cols[1].values[0],raw,subName,showName,codeValue);
                        p.cols[2].values = three.map(function (d) {
                            return d[codeValue];
                        });
                        p.cols[2].displayValues = three.map(function (d) {
                            return d[showName];
                        });
                    }
                }
            }
            $(this).picker(p);
        });
    };

    defaults = $.fn.cascadePicker.prototype.defaults = {
        raw:[], //级联数据
        showThree: true, //是否显示第三级
        subName:'sub',
        showName:'name',
        codeValue:'code'
    };

}($);
